#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Blueprint,render_template,session
from ..database import Article, Comment
from ..secure import login_required



bp = Blueprint('detail', __name__, url_prefix="/detail")

@bp.route('/anchor/<int:anchor>')
def detail(anchor):

    # 获取指定id的对象信息
    obj = Article.query.filter(Article.id==anchor).first()
    # 获取指定id的评论量
    obj_comment = Comment.query.filter_by(article_id=anchor).all()
    comment_num = len(obj_comment)

    cursor = Article.query
    # 数据量
    total = cursor.count()
    
    # 构造上一条信息
    be_id = anchor-1 if anchor>1 and total > 1 else anchor
    before_article={
        'be_id': be_id,
        'be_title': Article.query.filter(Article.id==be_id).first()
    }

    # 构造下一条信息
    next_id = anchor+1 if anchor < total else anchor
    next_article={
        'next_id': next_id,
        'next_title': Article.query.filter(Article.id==next_id).first()
    }
    
    ses = ''
    if 'user' in session and session['user'] is not None:
        ses = session['user']["name"]
    return render_template('/pages/detail.html',
                         data=obj,
                         before_article=before_article,
                         next_article=next_article, 
                         comment_num=comment_num,
                         ses=ses
     )
